﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jayden.Dll.Core.Collections.Generic
{
	public class Tree<T> : ITree<T>
	{
		private ITree<T> m_Parent;
		private T m_Value;
		private List<ITree<T>> m_Children = new List<ITree<T>>();

		public ITree<T> Parent
		{
			get { return m_Parent; }
			set
			{
				if (m_Parent == value)
					return;
				m_Parent = value;
			}
		}

		public T Value { get { return m_Value; } set { m_Value = value; } }

		public ITree<T> this[int index]
		{
			get { return m_Children[index]; }
			set
			{
				if (value == m_Children[index])
					return;
				if (m_Children[index].Parent != null)
					m_Children[index].Parent = null;
				m_Children[index] = value;
				if (m_Children[index].Parent != null)
					m_Children[index].Parent = this;
			}
		}

		public int Count { get { return m_Children.Count; } }
		public bool IsLeaf { get { return m_Children == null || m_Children.Count == 0; } }


		public bool IsRoot { get { return m_Parent == null; } }
		public ITree<T> Root { get { return IsRoot ? this : m_Parent.Root; } }

		public void AddChild(ITree<T> child)
		{
			if (child.Parent != null)
				child.Parent = null;
			m_Children.Add(child);
			child.Parent = this;
		}

		public bool RemoveChild(ITree<T> child)
		{
			if (m_Children.Remove(child))
			{
				child.Parent = null;
				return true;
			}
			return false;
		}
	}
}
